﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Helpers;
using projectManagementWeb.Models;
using projectManagementWeb.Models.ProjectLeader;
using System.Web.Security;
using System.Diagnostics;

namespace projectManagementWeb.Controllers
{
    public class ProjectLeaderController : Controller
    {
        private projectmanagementDBDataContext _dbContext;

        public ProjectLeaderController()
        {
            Init(); 
        }

        private void Init()
        {
            _dbContext = new projectmanagementDBDataContext();
        }

        //
        // GET: /ProjectLEader/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult PostIndex()
        {
            //Get the user ID
            ISingleResult<aspnet_User> users = _dbContext.spGetUser(User.Identity.Name);
            int userID = 0;
            foreach(aspnet_User user in users)
            {
                userID = user.id;
                break;
            }

            //Get the project data
            ISingleResult<spGetProjectsByProjectLeaderIDResult> projects = _dbContext.spGetProjectsByProjectLeaderID(userID);
            int projectID = 0;
            foreach (spGetProjectsByProjectLeaderIDResult project in projects)
            {
                projectID = project.ID;
                break;
            }

            //Get the project tasks
            ISingleResult<spGetProjectTasksResult> tasks = _dbContext.spGetProjectTasks(projectID);
            foreach (spGetProjectTasksResult task in tasks)
            {
                //Simple case, just need to update
                if (task.isDeleted == null || task.isDeleted == false)
                {
                    task.startDateBaseLine = task.startDate;
                    task.endDateBaseLine = task.endDate;
                    task.taskEffortBaseLine = task.taskEffortPlanned;
                    //Commit to the database
                    _dbContext.spSetBaseLine(task.startDateBaseLine, task.endDateBaseLine, task.taskEffortBaseLine, task.ID);
                }
                else
                {
                    _dbContext.spDestroyTask(task.ID);
                }
            }
            
            return View("Index");
        }

        public ActionResult ModuleIndex()
        {
            return View();
        }


        #region ProjectTasksForm Methods

        /// <summary>
        /// Método para obtener el proyecto que esta coordinando un usuario
        /// determinado
        /// </summary>
        /// <param name="username">Nombre del usuario</param>
        /// <returns></returns>
        public string GetUserProject(string username)
        {
            string result = null;

            ISingleResult<spGetUserProjectResult> temp = _dbContext.spGetUserProject(username);

            foreach (spGetUserProjectResult project in temp)
            {
                result = project.name;
                break;
            }

            return result;
        }

        /// <summary>
        /// Method to populate the GUI
        /// </summary>
        /// <returns>Viewbag with a ProjectLeadTaskListModel</returns>
        public ActionResult ProjectTasksForm()
        {
            ISingleResult<spGetUserProjectResult> temp = _dbContext.spGetUserProject(User.Identity.Name);

            int projectID = 0;
            int projectLeaderID = 0;

            foreach (spGetUserProjectResult project in temp)
            {
                projectID = project.ID;
                projectLeaderID = project.projectLeaderID;
                //projectID = project.projectLeaderID;
                break;
            }

            //Create the model instance
            ProjectLeadTaskListModel content = new ProjectLeadTaskListModel();
            content.ProjectLeaderID = projectLeaderID;
            content.TaskList = new List<ProjectLeadTaskDescriptionModel>();

            //Populate the tasklist
            ISingleResult<spGetProjectTasksResult> tempResult = _dbContext.spGetProjectTasks(projectID);

            foreach (spGetProjectTasksResult singleTask in tempResult)
            {
                if (singleTask.isDeleted == true)
                    continue;
                ProjectLeadTaskDescriptionModel taskModel = new ProjectLeadTaskDescriptionModel();
                taskModel.CurrentEffortDone = (int)singleTask.taskRealEffort;
                taskModel.CurrentEffortPending = (int)singleTask.taskEffortPending;
                taskModel.CurrentStatus = (int)singleTask.tStatusID;
                taskModel.EndDate = singleTask.endDate;
                taskModel.IsSelected = false;
                try
                {
                    taskModel.ModuleID = (int)singleTask.moduleID;
                }
                catch (Exception)
                {
                    //Nothing
                }
                taskModel.PlannedEstimate = (int)singleTask.taskEffortPlanned;
                taskModel.ProjectID = singleTask.projectID;
                try
                {
                    taskModel.ResourceID = (int)singleTask.userID;
                }
                catch (Exception )
                {
                    //Nothing
                }
                taskModel.StartDate = singleTask.startDate;
                taskModel.TaskDescription = singleTask.description;
                taskModel.TaskID = singleTask.ID;
                taskModel.TaskName = singleTask.name;

                content.TaskList.Add(taskModel);
          
            }
            return View(content);
        }
        [HttpPost]
        public ActionResult ProjectTasksForm(ProjectLeadTaskListModel model)
        {
            //Evaluate the model first
            if (ModelState.IsValid)
            {
                //Swap the model
                foreach (ProjectLeadTaskDescriptionModel task in model.TaskList)
                {
                    if (task.IsSelected)
                    {
                        //Must delete the task
                        _dbContext.spRemoveTask(task.TaskID);
                    }
                    else
                    {
                        _dbContext.spUpdateProjectTask(task.TaskID,
                                                        task.StartDate,
                                                        task.EndDate,
                                                        task.PlannedEstimate,
                                                        task.CurrentEffortDone,
                                                        task.CurrentEffortPending,
                                                        task.CurrentStatus,
                                                        task.ResourceID,
                                                        task.ModuleID);
                    }
                }


                return View("Index");
            }

            
            //Redisplay the model, with or without errors
            return View(model);
        }

        

        #endregion

        //
        // POST: /ProjectLEader/Create

        public ActionResult CreateTask()
        {     

            TaskDescriptionModel2 model = new TaskDescriptionModel2();
            try
            {
                model.userID = _dbContext.spGetUser(User.Identity.Name).First().id;
                model.ProjectID = _dbContext.spGetProjectID(model.userID).First().ID;
                ViewBag.projectID = model.ProjectID;

                model.StartDate = DateTime.Now;
                model.EndDate = DateTime.Now;
            }
            catch (Exception)
            {
                ViewBag.projectID = 0;
                return View();
            }

            return View(model);
            

         }

        [HttpPost]
        public ActionResult CreateTask(TaskDescriptionModel2 task)
        {
            if (ModelState.IsValid)
            {
                int userID = 0;
                int projectID = 0;

                try
                {
                    userID = _dbContext.spGetUser(User.Identity.Name).First().id;
                    projectID = _dbContext.spGetProjectID(userID).First().ID;
                    ViewBag.projectID = projectID;
                    task.ProjectID = projectID;
                    task.userID = userID;

                }
                catch (Exception)
                {
                    ViewBag.projectID = 0;
                    return View();

                }

                try
                {
                    var task2 = _dbContext.spCreateTask(task.TaskName, task.TaskDescription, null, task.ModuleID, projectID, task.PlannedEstimate, 10, task.StartDate, task.EndDate);

                    if (task2 == 1)
                    {
                        return RedirectToAction("ProjectTasksForm", "ProjectLeader");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Ocurrió un error al crear la tarea. Por favor, inténtelo de nuevo.");
                    }

                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Ocurrió un error al crear la tarea. Por favor, inténtelo de nuevo.");

                }

            }

            return View(task);
        }

        public ActionResult TaskDescription(int taskID)
        {
            ISingleResult<spGetTaskResult> tasks = _dbContext.spGetTask(taskID);
            TaskDescriptionModel model = new TaskDescriptionModel();

            foreach (spGetTaskResult task in tasks)
            {
                model.TaskID = taskID;
                model.TaskName = task.name;
                model.TaskDescription = task.description;
                model.StartDate = task.startDate;
                model.EndDate = task.endDate;
                model.CurrentEffortDone = (int)task.taskRealEffort;
                model.CurrentEffortPending = (int)task.taskEffortPending;
                model.PlannedEstimate = (int)task.taskEffortPlanned;

                try
                {
                    //Get the status for the Task
                    ISingleResult<spGetStatusNameResult> statusName = _dbContext.spGetStatusName(task.tStatusID);                   
                    model.CurrentStatusName = statusName.First().name;
                    if (task.tStatusID == 16 || task.tStatusID == 20)
                    {
                        ViewBag.status = "completed";
                        model.RealEndDate = (DateTime)task.realEndDate;
                    }
                    else {
                        ViewBag.status = "Notcompleted";
                    }
                }
                catch (InvalidOperationException )
                {
                    //Do nothing
                }

                try
                {
                    ISingleResult<spGetTaskModuleResult> moduleName = _dbContext.spGetTaskModule(taskID);
                    model.ModuleName = moduleName.First().name;
                }
                catch (InvalidOperationException)
                {
                    //Do nothing
                }

                try
                {
                    //Get the project for the Task
                    ISingleResult<spGetTaskProjectResult> projectName = _dbContext.spGetTaskProject(taskID);
                    model.ProjectName = projectName.First().name;
                }
                catch (InvalidOperationException)
                {
                    //Do nothing
                }
            }

            return View(model);
        }

        [HttpGet]
        public ActionResult ProjectLeaderReportsForm()
        {
            getProjectsByID();
            
            List<ModuleDescriptionModel> modules = getModulesByID();
            ViewBag.modules = modules;

            List<ResourceDescriptionModel> resources = getResourcesByProjectID();
            ViewBag.resources = resources;

            return View();
        }

        [HttpPost]
        public ActionResult ProjectLeaderReportsForm(ProjectLeaderReportFormModel model)
        {
            /*
            Debug.WriteLine("model.moduleID: " + model.moduleID);
            Debug.WriteLine("model.reportType: " + model.reportType);
            Debug.WriteLine("model.resourceID: " + model.resourceID);
            Debug.WriteLine("model.units: " + model.units); */

            if (ModelState.IsValid)
            {
                if (model. reportType.Equals("ValorGanado"))
                {
                    return RedirectToAction("EVChart", model);
                }
                else if (model.reportType.Equals("Tareas"))
                {
                    return RedirectToAction("TaskProgressChart", model);
                }
            } 

            return RedirectToAction("Index", model); 

        }

        private void getProjectsByID()
        {
            int userId = _dbContext.spGetUser(User.Identity.Name).First().id;

            List<string> proyectos = new List<string>();
            ISingleResult<spGetProjectsBySponsorIDResult> projectList = _dbContext.spGetProjectsBySponsorID(userId);

            foreach (spGetProjectsBySponsorIDResult item in projectList)
            {
                proyectos.Add(item.name);

            }

            ViewBag.proyectos = proyectos;

        }

        private List<ModuleDescriptionModel> getModulesByID()
        {
            int userId = _dbContext.spGetUser(User.Identity.Name).First().id;

            ISingleResult<spGetProjectModulesResult> modulesList = _dbContext.spGetProjectModules(userId);
            List<ModuleDescriptionModel> modules = new List<ModuleDescriptionModel>();


            foreach (spGetProjectModulesResult item in modulesList)
            {
                ModuleDescriptionModel model = new ModuleDescriptionModel();
                
                if (!item.name.Equals("Ninguno")) {
                    model.ID = item.ID;         
                    model.ProjectID = item.projectID;         
                    model.Name = item.name;         
                    model.Description = item.description;         
                    model.StartDate = (DateTime)item.startDate;         
                    model.EndDate = (DateTime)item.endDate;         
                    model.Created = (DateTime)item.created;         
                    model.Updated = (DateTime)item.updated;
                    modules.Add(model);
                }
         
            }

            return modules;

        }

        private List<ResourceDescriptionModel> getResourcesByProjectID()
        {
            int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
            
            // We assume every projectleader has at most 1 active project, otherwise, we return the first project found 

            spGetActiveProjectResult activeProject = null;

            try
            {
                activeProject = _dbContext.spGetActiveProject(userId).First();
            }
            catch (InvalidOperationException )
            {
                // do nothing
            }

            List<ResourceDescriptionModel> resources = new List<ResourceDescriptionModel>();
            
            if (activeProject != null)
            {
                ISingleResult<spGetAssignedResourcesByProjectIDResult> cursorResources = _dbContext.spGetAssignedResourcesByProjectID(activeProject.ID);
                foreach (spGetAssignedResourcesByProjectIDResult item in cursorResources)
                {
                    ResourceDescriptionModel model = new ResourceDescriptionModel();

                    model.userID = item.id;
                    model.Username = item.UserName;
                    model.FirstName = item.FirstName;
                    model.LastName = item.LastName;
                    model.FullName = item.FirstName + " " + item.LastName;

                    resources.Add(model);

                }

            }

            return resources;
        }

        private List<spGetModuleByProjectIDResult> GetModule(int projectId)
        {
            return _dbContext.spGetModuleByProjectID(projectId).ToList();
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult loadModulesByProjectID(string id)
        {
            try
            {
                var moduleData = _dbContext.spGetModuleByProjectID(Convert.ToInt32(id)).Select(m => new SelectListItem()
                {
                    Value = m.ID.ToString(),
                    Text = m.name.ToString()

                });
                return Json(moduleData, JsonRequestBehavior.AllowGet);
            }
            catch(Exception)
            {
                spGetModuleByProjectIDResult moduleData = new spGetModuleByProjectIDResult();
                return Json(moduleData, JsonRequestBehavior.AllowGet);
            }
            
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult loadModuleInfo(string id)
        {
            try
            {
                var moduleData = _dbContext.spGetModuleByID(Convert.ToInt32(id)).First();
                Hashtable h = new Hashtable();
                h.Add("ID", moduleData.ID.ToString());
                h.Add("name", moduleData.name);
                h.Add("projectID", moduleData.projectID.ToString());
                h.Add("startDate", moduleData.startDate.ToString());
                h.Add("endDate", moduleData.endDate.ToString());
                h.Add("description", moduleData.description);

                
                return Json(h, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                spGetModuleByIDResult moduleData = new spGetModuleByIDResult();
                return Json(moduleData, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult modifyModule()
        {
            modifyModuleModel model = new modifyModuleModel();
            model.userID = _dbContext.spGetUser(User.Identity.Name).First().id;
            model.startDate = DateTime.Now;
            model.endDate = DateTime.Now;
            return View(model);
        }
        [HttpPost]
        public ActionResult modifyModule(modifyModuleModel model)
        {
            if (ModelState.IsValid)
            {
                int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
                // Attempt to register the user
                projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();

                int resultStatus = pmwDB.spUpdateModule(model.ID, model.Name, model.Description, model.projectID, model.startDate, model.endDate);

                if (resultStatus == 1)
                {
                    return RedirectToAction("Index", "ProjectLeader");
                }
                else
                {
                    ModelState.AddModelError("", "An errror Ocurred while creating the module.");
                }
                 
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult createModule()
        {
            /*int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
            IEnumerable<SelectListItem> projectID = _dbContext.spGetProjectsByProjectLeaderID(userId)
            .Select(i => new SelectListItem
            {
                Value = i.ID.ToString(),
                Text = i.name.ToString()
            });
            ViewBag.projectID = projectID;*/
            createModuleModel model = new createModuleModel();
            model.userID = _dbContext.spGetUser(User.Identity.Name).First().id;
            model.startDate = DateTime.Now;
            model.endDate = DateTime.Now;
            return View(model);
        }
        [HttpPost]
        public ActionResult createModule(createModuleModel model)
        {
            if (ModelState.IsValid)
            {
                int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
                // Attempt to register the user
                projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();
                
                int createStatus = pmwDB.spCreateModule(model.Name, model.Description,model.projectID, model.startDate, model.endDate);

                if (createStatus == 1)
                {
                    return RedirectToAction("Index", "ProjectLeader");
                }
                else
                {
                    ModelState.AddModelError("", "An errror Ocurred while creating the module.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult deleteModule()
        {
            deleteModuleModel model = new deleteModuleModel();
            model.userID = _dbContext.spGetUser(User.Identity.Name).First().id;
            return View(model);
        }
        [HttpPost]
        public ActionResult deleteModule(deleteModuleModel model)
        {
            if (ModelState.IsValid)
            {
                int userId = _dbContext.spGetUser(User.Identity.Name).First().id;
                // Attempt to register the user
                projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();

                int resultStatus = pmwDB.spDeleteModuleAndItsTasks(model.ID);

                if (resultStatus == 1)
                {
                    return RedirectToAction("Index", "ProjectLeader");
                }
                else
                {
                    ModelState.AddModelError("", "An errror Ocurred while deleting the module.");
                }

            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }


        [HttpGet]
        public ActionResult ProjectLeaderAssignResourcesform()
        {
            ISingleResult<spGetListAvailableResourcesResult> listaRecursos = _dbContext.spGetListAvailableResources();
            List<ProjectLeaderAssignResources> recursos = new List<ProjectLeaderAssignResources>();

            foreach (spGetListAvailableResourcesResult resource in listaRecursos)
            {
                ProjectLeaderAssignResources recurso = new ProjectLeaderAssignResources();
                recurso.id = resource.id;
                recurso.FirstName = resource.FirstName;
                recurso.LastName = resource.LastName;
                recursos.Add(recurso);
            }

            ViewBag.recursos = recursos;
            return View();

        }

        [HttpPost]
        public ActionResult ProjectLeaderAssignedTasksform(int userId)
        {

            projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();
            var projectID = 0;
            try
            {
                var VuserID = pmwDB.spGetUser(User.Identity.Name).First().id;
                projectID = pmwDB.spGetProjectID(VuserID).First().ID;
                ViewBag.projectID = projectID;
            }
            catch(Exception exception) 
            {
                ViewBag.projectID = 0;
            }
            ISingleResult<spGetListAssignedTasksResult> listaRecursos = _dbContext.spGetListAssignedTasks(projectID, userId);

            List<ProjectLeaderAssignedTask> tareas = new List<ProjectLeaderAssignedTask>();

            foreach (spGetListAssignedTasksResult task in listaRecursos)
            {
                ProjectLeaderAssignedTask tarea = new ProjectLeaderAssignedTask();
                tarea.ID = task.ID;
                tarea.name = task.name;
                tarea.description = task.description;
                tarea.ProjectID = task.projectID;
                tarea.StartDate = task.startDate;
                tarea.EndDate = task.endDate;
                tarea.taskEffortPlanned = (int)task.taskEffortPlanned;
                tarea.taskEffortPending = (int)task.taskEffortPending;
                tarea.taskRealEffort = (int)task.taskRealEffort;

                ISingleResult<spGetStatusNameResult> statusName = _dbContext.spGetStatusName(task.tStatusID);
                tarea.CurrentStatusName = statusName.First().name;

                tareas.Add(tarea);
            }

            ViewBag.tareas = tareas;

            return View();
        }

        [HttpPost]
        public ActionResult assignTasks(FormCollection collection, int userId)
        {
            projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();

            foreach (var key in collection.Keys)
            {
                if (key.ToString().StartsWith("AsignarTarea"))
                {
                    int taskID = int.Parse(key.ToString().Replace("AsignarTarea", ""));
                    if (collection[key.ToString()].Contains("true"))
                    {
                        //Debug.WriteLine("TaskID: " + taskID + " has been selected, UserID: " + userId);
                        pmwDB.spUpdateTaskUserId(taskID, userId);
                    }
                }
            }

            return RedirectToAction("ProjectLeaderAssignResourcesform");

        }


        [HttpPost]
        public ActionResult ProjectLeaderAvailableTasksform(int userId)
        {

            projectmanagementDBDataContext pmwDB = new projectmanagementDBDataContext();
            var projectID = 0;
            try
            {
                var VuserID = pmwDB.spGetUser(User.Identity.Name).First().id;
                projectID = pmwDB.spGetProjectID(VuserID).First().ID;
                ViewBag.projectID = projectID;
            }
            catch(Exception exception)
            {
                ViewBag.projectID = 0;
            }

            ISingleResult<spGetListAvailableTasksResult> listaTareas = _dbContext.spGetListAvailableTasks(projectID);

            List<ProjectLeaderAvailableTask> tareas = new List<ProjectLeaderAvailableTask>();

            foreach (spGetListAvailableTasksResult task in listaTareas)
            {
                ProjectLeaderAvailableTask tarea = new ProjectLeaderAvailableTask();
                tarea.ID = task.ID;
                tarea.name = task.name;
                tarea.description = task.description;
                tarea.ProjectID = task.projectID;
                tarea.StartDate = task.startDate;
                tarea.EndDate = task.endDate;
                tarea.taskEffortPlanned = (int)task.taskEffortPlanned;
                tarea.taskEffortPending = (int)task.taskEffortPending;
                tarea.taskRealEffort = (int)task.taskRealEffort;

                tareas.Add(tarea);
            }

            ViewBag.tareas = tareas;
            ViewBag.userId = userId;

            return View();
        }



        public List<TaskDescriptionModel> GetTasks(ProjectLeaderReportFormModel model)
        {
            List<TaskDescriptionModel> tasksResult = new List<TaskDescriptionModel>();

            int projectLid = _dbContext.spGetUser(User.Identity.Name).First().id;
            int projectID = _dbContext.spGetProjectID(projectLid).First().ID;

            ISingleResult<spTasksInProgressDevResult> developerTasks;// = _dbContext.sp
            ISingleResult<spTasksInProgressProjectResult> projectTasks;
            ISingleResult<spTasksInProgressModResult> moduleTasks;
            if (model.moduleID == 0 && model.resourceID == 0)
            {
                projectTasks = _dbContext.spTasksInProgressProject(projectID);

                foreach (spTasksInProgressProjectResult task in projectTasks)
                {
                    TaskDescriptionModel realTask = new TaskDescriptionModel();
                    realTask.TaskID = task.ID;
                    realTask.TaskName = task.name;
                    realTask.StartDate = task.startDate;
                    realTask.EndDate = task.endDate;
                    realTask.PlannedEstimate = (int)task.taskEffortPlanned;
                    realTask.CurrentEffortDone = (int)task.taskRealEffort;
                    realTask.CurrentEffortPending = (int)task.taskEffortPending;
                    realTask.CurrentStatus = (int)task.tStatusID;

                    //Get the module for the Task
                    ISingleResult<spGetTaskModuleResult> moduleResult = _dbContext.spGetTaskModule(task.ID);
                    foreach (spGetTaskModuleResult module in moduleResult)
                    {
                        realTask.ModuleName = module.name;
                        realTask.ModuleID = module.ID;
                    }

                    tasksResult.Add(realTask);

                }
            }
            else if (model.moduleID != 0)
            {
                moduleTasks = _dbContext.spTasksInProgressMod(model.moduleID, projectID);

                foreach (spTasksInProgressModResult task in moduleTasks)
                {
                    TaskDescriptionModel realTask = new TaskDescriptionModel();
                    realTask.TaskID = task.ID;
                    realTask.TaskName = task.name;
                    realTask.StartDate = task.startDate;
                    realTask.EndDate = task.endDate;
                    realTask.PlannedEstimate = (int)task.taskEffortPlanned;
                    realTask.CurrentEffortDone = (int)task.taskRealEffort;
                    realTask.CurrentEffortPending = (int)task.taskEffortPending;
                    realTask.CurrentStatus = (int)task.tStatusID;

                    //Get the module for the Task
                    ISingleResult<spGetTaskModuleResult> moduleResult = _dbContext.spGetTaskModule(task.ID);
                    foreach (spGetTaskModuleResult module in moduleResult)
                    {
                        realTask.ModuleName = module.name;
                        realTask.ModuleID = module.ID;
                    }

                    tasksResult.Add(realTask);

                }
            }
            else if (model.resourceID != 0)
            {
                developerTasks = _dbContext.spTasksInProgressDev(model.resourceID, projectID);

                foreach (spTasksInProgressDevResult task in developerTasks)
                {
                    TaskDescriptionModel realTask = new TaskDescriptionModel();
                    realTask.TaskID = task.ID;
                    realTask.TaskName = task.name;
                    realTask.StartDate = task.startDate;
                    realTask.EndDate = task.endDate;
                    realTask.PlannedEstimate = (int)task.taskEffortPlanned;
                    realTask.CurrentEffortDone = (int)task.taskRealEffort;
                    realTask.CurrentEffortPending = (int)task.taskEffortPending;
                    realTask.CurrentStatus = (int)task.tStatusID;

                    //Get the module for the Task
                    ISingleResult<spGetTaskModuleResult> moduleResult = _dbContext.spGetTaskModule(task.ID);
                    foreach (spGetTaskModuleResult module in moduleResult)
                    {
                        realTask.ModuleName = module.name;
                        realTask.ModuleID = module.ID;
                    }

                    tasksResult.Add(realTask);

                }

            }

            return tasksResult;
        }

        public ActionResult TaskProgressChart(ProjectLeaderReportFormModel model)
        {
            if (ModelState.IsValid)
            {

                List<string> id = new List<string>();
                List<int> ee = new List<int>();
                List<int> er = new List<int>();
                List<int> ef = new List<int>();
                String[] xLabel = { " ", "Total de tareas" };
                int[] eeTot = new int[2] { 0, 0 };
                int[] erTot = new int[2] { 0, 0 };
                int[] efTot = new int[2] { 0, 0 };
                int index = 1;
                float width_chart = 0;
                ViewBag.ValidDate = "true";
                
                DateTime startDate = DateTime.Today; ;
                DateTime today = DateTime.Today;

                int projectLid = 0; 
                int projectID = 0;  

                try
                {
                    projectLid = _dbContext.spGetUser(User.Identity.Name).First().id;
                    projectID = _dbContext.spGetProjectID(projectLid).First().ID;
                    ViewBag.projectID = projectID;

                }
                catch (Exception)
                {
                    ViewBag.projectID = 0;
                    return View();
                }

                TaskListModel taskList = new TaskListModel();
                taskList.taskList = this.GetTasks(model);
                ISingleResult<spTasksInProgressDevResult> developerTasks;// = _dbContext.sp
                ISingleResult<spTasksInProgressProjectResult> projectTasks;
                ISingleResult<spTasksInProgressModResult> moduleTasks;        


                if (model.moduleID == 0 && model.resourceID == 0) // report by project
                {
                    startDate = (DateTime)_dbContext.spGetProjectStartDate(projectID).First().startDate;
                }
                else if (model.moduleID != 0)  // report by module
                {
                    startDate = (DateTime)_dbContext.spGetModuleStartDate(model.moduleID).First().startDate;

                }
                else if (model.resourceID != 0)  // report by developer
                {
                    startDate = (DateTime)_dbContext.spGetProjectStartDate(projectID).First().startDate;
                }

                if (startDate.Date > today.Date)
                {
                    ViewBag.ValidDate = "false";
                    ViewBag.startDate = startDate;
                    return View();
                }
          
                if (model.moduleID == 0 && model.resourceID == 0)
                {
                    projectTasks = _dbContext.spTasksInProgressProject(projectID);
                    
                    foreach (spTasksInProgressProjectResult progressTask in projectTasks)
                    {
                        id.Add(" ");
                        id.Add("#" + index.ToString());
                        index = index + 1;
                        //id.Add(" " + progressTask.ID);                    

                        ee.Add((int)progressTask.taskEffortPlanned);
                        ee.Add(0);

                        er.Add(0);
                        er.Add((int)progressTask.taskRealEffort);

                        ef.Add(0);
                        ef.Add((int)progressTask.taskEffortPending);

                        eeTot[0] = eeTot[0] + (int)progressTask.taskEffortPlanned;
                        erTot[1] = erTot[1] + (int)progressTask.taskRealEffort;
                        efTot[1] = efTot[1] + (int)progressTask.taskEffortPending;
                    }

                } else if( model.moduleID != 0 )
                {
                   
                    moduleTasks = _dbContext.spTasksInProgressMod(model.moduleID, projectID);

                    foreach (spTasksInProgressModResult progressTask in moduleTasks)
                    {
                        id.Add(" ");
                        id.Add("#" + index.ToString());
                        index = index + 1;
                        //id.Add(" " + progressTask.ID);                    

                        ee.Add((int)progressTask.taskEffortPlanned);
                        ee.Add(0);

                        er.Add(0);
                        er.Add((int)progressTask.taskRealEffort);

                        ef.Add(0);
                        ef.Add((int)progressTask.taskEffortPending);

                        eeTot[0] = eeTot[0] + (int)progressTask.taskEffortPlanned;
                        erTot[1] = erTot[1] + (int)progressTask.taskRealEffort;
                        efTot[1] = efTot[1] + (int)progressTask.taskEffortPending;
                    }


                }
                else if (model.resourceID != 0) 
                {
                   
                    developerTasks = _dbContext.spTasksInProgressDev(model.resourceID, projectID);

                    foreach (spTasksInProgressDevResult progressTask in developerTasks)
                    {
                        id.Add(" ");
                        id.Add("#" + index.ToString());
                        index = index + 1;
                        //id.Add(" " + progressTask.ID);                    

                        ee.Add((int)progressTask.taskEffortPlanned);
                        ee.Add(0);

                        er.Add(0);
                        er.Add((int)progressTask.taskRealEffort);

                        ef.Add(0);
                        ef.Add((int)progressTask.taskEffortPending);

                        eeTot[0] = eeTot[0] + (int)progressTask.taskEffortPlanned;
                        erTot[1] = erTot[1] + (int)progressTask.taskRealEffort;
                        efTot[1] = efTot[1] + (int)progressTask.taskEffortPending;
                    }

                }

               
                if (model.detail.Equals("Individual"))
                {
                    if (id.Count == 0)
                    {
                        id.Add("0 tareas en progreso");
                        ee.Add(0);
                        er.Add(0);
                        ef.Add(0);
                    }

                    if (id.Count < 8) width_chart = 800;
                    else
                    {
                        width_chart = (float)id.Count() / 8;
                        width_chart = width_chart * 800;
                    }

                    var chart = new Chart(width: (int)width_chart, height: 600, theme: ChartTheme.Blue)
                        .AddTitle("Tareas en progreso individuales")
                        .AddSeries(chartType: "StackedColumn",
                        xValue: id,
                        yValues: ee,
                        name: "Esfuerzo estimado")
                        .AddSeries(chartType: "StackedColumn",
                        xValue: id,
                        yValues: er,
                        name: "Esfuerzo real")
                        .AddSeries(chartType: "StackedColumn",
                        xValue: id,
                        yValues: ef,
                        name: "Esfuerzo faltante")
                        .AddLegend()
                        .SetXAxis(title: "# de tarea")
                        .SetYAxis(title: "Tiempo (horas)")
                        //.Write();
                        .GetBytes("jpeg");
                    //return View(model);
                    //return File(chart, "image/jpeg");

                    var base64Data = Convert.ToBase64String(chart);
                    ViewBag.ImageData = base64Data;
                    ViewBag.ImageContentType = "image/jpeg";

                    return View(taskList);
                }
                else if (model.detail.Equals("Total"))
                {
                    if (id.Count == 0)
                    {
                        xLabel[0] = " ";
                        xLabel[1] = "0 tareas en progreso";
                    }
                    var chart = new Chart(width: 800, height: 600, theme: ChartTheme.Blue)
                         .AddTitle("Total de tareas en progreso")
                         .AddSeries(chartType: "StackedColumn",
                         xValue: xLabel,
                         yValues: eeTot,
                         name: "Esfuerzo estimado total")
                         .AddSeries(chartType: "StackedColumn",
                         xValue: xLabel,
                         yValues: erTot,
                         name: "Esfuerzo real total")
                         .AddSeries(chartType: "StackedColumn",
                         xValue: xLabel,
                         yValues: efTot,
                         name: "Esfuerzo faltante total")
                         .AddLegend()
                         .SetXAxis(title: "Tareas")
                         .SetYAxis(title: "Tiempo (horas)")
                        //.Write();
                         .GetBytes("jpeg");

                    //return View(model);
                    //return File(chart, "image/png");

                    var base64Data = Convert.ToBase64String(chart);
                    ViewBag.ImageData = base64Data;
                    ViewBag.ImageContentType = "image/jpeg";

                    return View(taskList);

                }

            }
            return View(model);
        }

        public ActionResult EVChart(ProjectLeaderReportFormModel model)
        {
            if (ModelState.IsValid)
            {
                DateTime today = DateTime.Today;
                DateTime startDate = DateTime.Today;
                DateTime endDate = DateTime.Today;
                DateTime startDateBL = DateTime.Today;
                DateTime endDateBL = DateTime.Today;
                DateTime reportDate;
                DateTime stopDate;
                TimeSpan tempSize;
                int index = 1;
                int moduleID;
                int developerId;
                int projectLid =0;  
                int projectID = 0;
                float width_chart = 0;
                ViewBag.ValidDate = "true";
                ISingleResult<spGetProjectIDResult> projectIDs = null;
                ISingleResult<spEVmoduloResult> moduleTasks = null;
                ISingleResult<spEVdevResult> developerTasks = null;
                ISingleResult<spEVprojectResult> projectTasks = null;
                ISingleResult<spEVmoduloResult> moduleTasks2 = null;
                ISingleResult<spEVdevResult> developerTasks2 = null;
                ISingleResult<spEVprojectResult> projectTasks2 = null;
                ISingleResult<spModuleBaseLineResult> moduleTasksBL = null;
                ISingleResult<spdevBaseLineResult> developerTasksBL = null;
                ISingleResult<spBaseLineResult> projectTasksBL = null;
                ISingleResult<spModuleBaseLineResult> moduleTasksBL2 = null;
                ISingleResult<spdevBaseLineResult> developerTasksBL2 = null;
                ISingleResult<spBaseLineResult> projectTasksBL2 = null;

                try
                {
                    projectLid = _dbContext.spGetUser(User.Identity.Name).First().id;
                    projectID = _dbContext.spGetProjectID(projectLid).First().ID;
                    ViewBag.projectID = projectID;
                }
                catch (Exception)                
                {
                    ViewBag.projectID = 0;
                    return View();
                }
                

                if (model.moduleID == 0 && model.resourceID == 0) // report by project
                {
                    try {
                        startDate = (DateTime)_dbContext.spGetProjectStartDate(projectID).First().startDate;
                        endDate = (DateTime)_dbContext.spGetProjectStartDate(projectID).First().endDate;    
                    }
                    catch (Exception)
                    {
                        //Nothing
                    }                
                    projectTasks = _dbContext.spEVproject(projectID);
                    projectTasks2 = _dbContext.spEVproject(projectID);
                    projectTasksBL = _dbContext.spBaseLine(projectID);
                    projectTasksBL2 = _dbContext.spBaseLine(projectID);
                    reportDate = startDate;
                   
                }
                else if (model.moduleID != 0)  // report by module
                {
                    moduleID = model.moduleID;
                    // create a sp to get the start date for module
                    try {
                        startDate = (DateTime)_dbContext.spGetModuleStartDate(model.moduleID).First().startDate;
                        endDate = (DateTime)_dbContext.spGetModuleStartDate(model.moduleID).First().endDate;
                    }
                    catch (Exception)
                    {
                        //Nothing
                    } 
                    moduleTasks = _dbContext.spEVmodulo(model.moduleID, projectID);
                    moduleTasks2 = _dbContext.spEVmodulo(model.moduleID, projectID);
                    moduleTasksBL = _dbContext.spModuleBaseLine(model.moduleID, projectID);
                    moduleTasksBL2 = _dbContext.spModuleBaseLine(model.moduleID, projectID);
                    reportDate = startDate;
                   
                }
                else if (model.resourceID != 0)  // report by developer
                {
                    developerId = model.resourceID;
                    try {
                        startDate = (DateTime)_dbContext.spGetProjectStartDate(projectID).First().startDate;
                        endDate = (DateTime)_dbContext.spGetProjectStartDate(projectID).First().endDate;
                    }
                    catch (Exception)
                    {
                        //Nothing
                    } 

                    developerTasks = _dbContext.spEVdev(model.resourceID, projectID);
                    developerTasks2 = _dbContext.spEVdev(model.resourceID, projectID);
                    developerTasksBL = _dbContext.spdevBaseLine(model.resourceID, projectID);
                    developerTasksBL2 = _dbContext.spdevBaseLine(model.resourceID, projectID);
                    reportDate = startDate;
                   
                }

                ViewBag.fechaFin = endDate;               

                if (model.moduleID == 0 && model.resourceID == 0)
                {
                    foreach (spEVprojectResult projectTask2 in projectTasks2)
                    {

                        if (projectTask2.tStatusID == 16 || projectTask2.tStatusID == 20)
                        {
                            if (projectTask2.realEndDate > endDate)
                            {
                                endDate = (DateTime)projectTask2.realEndDate;
                            } 
                        }
                
                                      
                    }
                    foreach (spBaseLineResult projectTaskBL2 in projectTasksBL2)
                    {
                        if (projectTaskBL2.endDateBaseLine > endDate)
                        {
                            endDate = (DateTime)projectTaskBL2.endDateBaseLine;
                        }
                        if (projectTaskBL2.startDateBaseLine < startDate) 
                        {
                            startDate = (DateTime)projectTaskBL2.startDateBaseLine;
                        }

                    }
                }
                else if (model.moduleID != 0)
                {
                    foreach (spEVmoduloResult modTask2 in moduleTasks2)
                    {
                        if (modTask2.tStatusID == 16 || modTask2.tStatusID == 20)
                        {
                            if (modTask2.realEndDate > endDate)
                            {
                                endDate = (DateTime)modTask2.realEndDate;
                            }
                        }

                    }
                    foreach (spModuleBaseLineResult moduleTaskBL2 in moduleTasksBL2)
                    {
                        if (moduleTaskBL2.endDateBaseLine > endDate)
                        {
                            endDate = (DateTime)moduleTaskBL2.endDateBaseLine;
                        }
                        if (moduleTaskBL2.startDateBaseLine < startDate)
                        {
                            startDate = (DateTime)moduleTaskBL2.startDateBaseLine;
                        }

                    }
                }
                else if (model.resourceID != 0)
                {
                    foreach (spEVdevResult devTask2 in developerTasks2)
                    {
                        if (devTask2.tStatusID == 16 || devTask2.tStatusID == 20)
                        {
                            if (devTask2.realEndDate > endDate)
                            {
                                endDate = (DateTime)devTask2.realEndDate;
                            }
                        }

                    }
                    foreach (spdevBaseLineResult devTaskBL2 in developerTasksBL2)
                    {
                        if (devTaskBL2.endDateBaseLine > endDate)
                        {
                            endDate = (DateTime)devTaskBL2.endDateBaseLine;
                        }
                        if (devTaskBL2.startDateBaseLine < startDate)
                        {
                            startDate = (DateTime)devTaskBL2.startDateBaseLine;
                        }

                    }
                }

                if (startDate.Date > today.Date)
                {
                    ViewBag.ValidDate = "false";
                    ViewBag.startDate = startDate;
                    return View();
                }

                if (endDate.Date >= today.Date)
                {
                    tempSize = today.Subtract(startDate);
                    stopDate = today;
                }
                else
                {
                    tempSize = endDate.Subtract(startDate);
                    stopDate = endDate;
                }

                int size;
                if ((tempSize.Days % 7) == 0)
                {
                    size = ((tempSize.Days) / 7) + 1;
                }
                else
                {
                    size = ((tempSize.Days) / 7) + 2;
                }

                float[] estadisticas = new float[5];

                float[] pv = new float[size];
                float[] ev = new float[size];
                float[] ac = new float[size];
                float[] bl = new float[size];
                float[] pvP = new float[size];
                float[] evP = new float[size];
                float[] acP = new float[size];
                float[] blP = new float[size];
                DateTime[] fechas = new DateTime[size];
                String[] fechas2 = new String[size];
                fechas[0] = startDate.Date;
                for (int i = 1; i < size; i++)
                {
                    if (fechas[i - 1].AddDays(7).Date < stopDate.Date)
                    {
                        fechas[i] = fechas[i - 1].AddDays(7).Date;
                    }
                    else
                    {
                        fechas[i] = stopDate.Date;
                    }

                }

                for (int i = 0; i < size; i++)
                {
                    pv[i] = 0;
                    ev[i] = 0;
                    ac[i] = 0;
                    bl[i] = 0;
                    pvP[i] = 0;
                    evP[i] = 0;
                    acP[i] = 0;
                    blP[i] = 0;
                }

                float eac = 0;

                if (model.moduleID == 0 && model.resourceID == 0)
                {
                    foreach (spEVprojectResult projectTask in projectTasks)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);
                        eac = eac + (float)projectTask.taskEffortPlanned;

                        if(projectTask.tStatusID != 17 ){
                        
                            if (projectTask.endDate.Date <= stopDate.Date)
                            {
                                while (projectTask.endDate.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                pv[index] = pv[index] + (float)projectTask.taskEffortPlanned;
                            }
                        }
                        index = 1;


                        if (projectTask.tStatusID == 16 || projectTask.tStatusID == 20)
                        {
                            reportDate = startDate;
                            reportDate = reportDate.AddDays(7);
                            if (projectTask.realEndDate.Value.Date <= stopDate.Date)
                            {

                                while (projectTask.realEndDate.Value.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                ev[index] = ev[index] + (float)projectTask.taskEffortPlanned;
                                ac[index] = ac[index] + (float)projectTask.taskRealEffort;
                            }                           
                        }
                        index = 1;
                    }



                    foreach (spBaseLineResult projectTaskBL in projectTasksBL)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);

                        if (projectTaskBL.endDateBaseLine.Value.Date <= stopDate.Date)
                        {
                            while (projectTaskBL.endDateBaseLine.Value.Date > reportDate.Date)
                            {
                                reportDate = reportDate.AddDays(7);
                                index = index + 1;
                            }
                            bl[index] = bl[index] + (float)projectTaskBL.taskEffortBaseLine;
                        }

                        index = 1;
                    }

                }
                else if (model.moduleID != 0)
                {
                    foreach (spEVmoduloResult modTask in moduleTasks)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);
                        eac = eac + (float)modTask.taskEffortPlanned;


                        if (modTask.tStatusID != 17)
                        {
                            if (modTask.endDate.Date <= stopDate.Date)
                            {
                                while (modTask.endDate.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                pv[index] = pv[index] + (float)modTask.taskEffortPlanned;
                            }
                        }


                        index = 1;

                        if (modTask.tStatusID == 16 || modTask.tStatusID == 20)
                        {
                            reportDate = startDate;
                            reportDate = reportDate.AddDays(7);
                            if (modTask.realEndDate <= stopDate)
                            {
                                while (modTask.realEndDate.Value.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                ev[index] = ev[index] + (float)modTask.taskEffortPlanned;
                                ac[index] = ac[index] + (float)modTask.taskRealEffort;
                            }

                           
                        }
                        index = 1;

                    }

                    foreach (spModuleBaseLineResult moduleTaskBL in moduleTasksBL)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);

                        if (moduleTaskBL.endDateBaseLine.Value.Date <= stopDate.Date)
                        {
                            while (moduleTaskBL.endDateBaseLine.Value.Date > reportDate.Date)
                            {
                                reportDate = reportDate.AddDays(7);
                                index = index + 1;
                            }
                            bl[index] = bl[index] + (float)moduleTaskBL.taskEffortBaseLine;
                        }

                        index = 1;
                    }

                }
                else if (model.resourceID != 0)
                {
                    foreach (spEVdevResult devTask in developerTasks)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);
                        eac = eac + (float)devTask.taskEffortPlanned;


                        if (devTask.tStatusID != 17)
                        {

                            if (devTask.endDate.Date <= stopDate.Date)
                            {
                                while (devTask.endDate.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                pv[index] = pv[index] + (float)devTask.taskEffortPlanned;
                            }
                        }


                        index = 1;

                        if (devTask.tStatusID == 16 || devTask.tStatusID == 20)
                        {
                            reportDate = startDate;
                            reportDate = reportDate.AddDays(7);
                            if (devTask.realEndDate.Value.Date <= stopDate.Date)
                            {
                                while (devTask.realEndDate.Value.Date > reportDate.Date)
                                {
                                    reportDate = reportDate.AddDays(7);
                                    index = index + 1;
                                }
                                ev[index] = ev[index] + (float)devTask.taskEffortPlanned;
                                ac[index] = ac[index] + (float)devTask.taskRealEffort;
                            }

                           
                        }
                        index = 1;

                    }


                    foreach (spdevBaseLineResult developerTaskBL in developerTasksBL)
                    {
                        reportDate = startDate;
                        reportDate = reportDate.AddDays(7);


                        if (developerTaskBL.endDateBaseLine.Value.Date <= stopDate.Date)
                        {
                            while (developerTaskBL.endDateBaseLine.Value.Date > reportDate.Date)
                            {
                                reportDate = reportDate.AddDays(7);
                                index = index + 1;
                            }
                            bl[index] = bl[index] + (float)developerTaskBL.taskEffortBaseLine;
                        }

                        index = 1;

                    }


                }

                for (int i = 1; i < size; i++)
                {
                    pv[i] = pv[i] + pv[i - 1];
                    ev[i] = ev[i] + ev[i - 1];
                    ac[i] = ac[i] + ac[i - 1];
                    bl[i] = bl[i] + bl[i - 1];
                }

                if (size < 40) width_chart = 800;
                else
                {
                    width_chart = (float)size / 40;
                    width_chart = width_chart * 800;
                }

                if (model.units.Equals("Horas"))
                {
                    var chart = new Chart(width: (int)width_chart, height: 600, theme: ChartTheme.Blue)
                         .AddTitle("Valor ganado en horas de construcción")
                         .AddSeries(chartType: "Line",
                        //xValue: xLabel,
                         yValues: pv,
                         name: "Valor planeado")
                        
                         .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                         yValues: bl,
                         name: "Línea base")      

                         .AddSeries(chartType: "Line",
                        //xValue: xLabel,
                         yValues: ev,
                         name: "Valor ganado")
                         .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                         yValues: ac,
                         name: "Costo actual")
                   
                         .AddLegend()
                         .SetXAxis(title: "Periodo de tiempo (semanas)")
                         .SetYAxis(title: "Avance en horas")
                        //.Write();
                          .GetBytes("jpeg");
                    //return File(chart, "image/png");

                    var base64Data = Convert.ToBase64String(chart);
                    ViewBag.ImageData = base64Data;
                    ViewBag.ImageContentType = "image/jpeg";
                    ViewBag.Symbol = "hrs.";
                    ViewBag.PV = pv;
                    ViewBag.EV = ev;
                    ViewBag.AC = ac;
                    ViewBag.BL = bl;

                }
                else if (model.units.Equals("Porcentaje"))
                {

                    if (eac != 0)
                    {
                        for (int i = 0; i < size; i++)
                        {
                            pvP[i] = (pv[i] / eac) * 100;
                            evP[i] = (ev[i] / eac) * 100;
                            acP[i] = (ac[i] / eac) * 100;
                            blP[i] = (bl[i] / eac) * 100;
                        }
                    }

                    var chart = new Chart(width: (int)width_chart, height: 600, theme: ChartTheme.Blue)
                          .AddTitle("Valor ganado en porcentaje")
                          .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                          yValues: pvP,
                          name: "Valor planeado")

                         .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                          yValues: blP,
                          name: "Línea base")

                          .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                          yValues: evP,
                          name: "Valor ganado")
                          .AddSeries(chartType: "Line",
                        // xValue: xLabel,
                          yValues: acP,
                          name: "Costo actual")

                          .AddLegend()
                          .SetXAxis(title: "Periodo de tiempo (semanas)")
                          .SetYAxis(title: "Avance en porcentaje (%)")
                        //.Write();
                          .GetBytes("jpeg");
                    //return File(chart, "image/png");

                    var base64Data = Convert.ToBase64String(chart);
                    ViewBag.ImageData = base64Data;
                    ViewBag.ImageContentType = "image/jpeg";
                    ViewBag.Symbol = "%";
                    ViewBag.PV = pvP;
                    ViewBag.EV = evP;
                    ViewBag.AC = acP; 
                    ViewBag.BL = blP;
                }

                // Calculando valores estadísticos
                estadisticas[0] = eac;
                estadisticas[1] = ev[size - 1] - ac[size - 1]; // Varianza costo
                estadisticas[2] = ev[size - 1] - pv[size - 1]; // varianza calendario
                if (ac[size - 1] == 0) estadisticas[3] = 0;
                else estadisticas[3] = ev[size - 1] / ac[size - 1]; // indice de costo
                if (pv[size - 1] == 0) estadisticas[4] = 0;
                else estadisticas[4] = ev[size - 1] / pv[size - 1]; // indice calendario
               
                ViewBag.fechas = fechas;
                ViewBag.size = fechas.Count();
                ViewBag.estadisticas = estadisticas;
                
                return View();

            }
            return RedirectToAction("Index");
        }

        

    }
}

